package com.fingard.dsp.bank.directbank.cpcn01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
/**
 *  中金支付交易对账单查询
 */
public class CPCN01Statement extends CPCN01Base implements IStatement {
	/**
	 * 日对账单查询
	 */
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm)	throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.writeStart();

		/** 获取交易对账分页*/
		String[] accStaRecRespHeader = getAccountStatement(p_reqQrySttm, retAts);
		String singlePayRecTotalNum = retAts.totalNum;
		WriteBankLogLn("交易对账分页总笔数:" + singlePayRecTotalNum);
		if (singlePayRecTotalNum.length() == 0) {
			singlePayRecTotalNum = "0";
		}

		/** 获取交易对账*/
		String[] statementRespHeader = getStatement(p_reqQrySttm, retAts);
		String singlePayTotalNum = retAts.totalNum;
		WriteBankLogLn("交易对账总笔数:" + singlePayTotalNum);
		if (singlePayTotalNum.length() == 0) {
			singlePayTotalNum = "0";
		}

		if (accStaRecRespHeader[0].equals("-1") && statementRespHeader[0].equals("-1")) {
			String respInfo = accStaRecRespHeader[1];
			if (StringHelper.isNullOrEmpty(respInfo)) {
				respInfo = statementRespHeader[1];
			}
			retAts.writeRespCode("-1");
			retAts.writeRespInfo(respInfo);
		} else {
			if (retAts.getWrittenRdCount() == 0) {
				retAts.writeRespCode("0");

				String respInfo = accStaRecRespHeader[1];
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = statementRespHeader[1];
				}
				retAts.writeRespInfo(respInfo);
			}

			int totalNum = Integer.parseInt(singlePayRecTotalNum) + Integer.parseInt(singlePayTotalNum);
			retAts.isWritedTotalNum(String.valueOf(totalNum));
		}

		retAts.writeEnd();
		return retAts;
	}

	private String[] getAccountStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"", ""};

		String respCode = "";
		String respInfo = "";
		retAts.totalNum = "0";
		int totalNum = 0;
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				if (actItem == null) {
					throw new Exception("未找到账号" + p_reqQrySttm.actNum + "对应的商户配置节点");
				} else {
					throw new Exception("账号" + p_reqQrySttm.actNum + "对应的证书文件不存在");
				}
			}

			// 拼请求报文
			CPCN01Header bankHeader = new CPCN01Header();
			bankHeader.transCode = "1811";

			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, bankHeader);

			xmlWriter.writeElementString("TxCode", bankHeader.transCode);
			xmlWriter.writeEndElement();
			xmlWriter.writeStartElement("Body");
			xmlWriter.writeElementString("InstitutionID", actItem.merchantId);
			xmlWriter.writeElementString("Date", Format.Date10Format.format(p_reqQrySttm.getBusDate()));
			xmlWriter.writeElementString("PageNO", "1");
			xmlWriter.writeElementString("CountPerPage", "1000");
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();

			// 请求报文
			WriteBankLogStep2(xmlWriter.toXmlString());

			// 发送银行
			String[] tmpStrRet = sendToBank("sync", xmlWriter.toXmlString(), actItem);

			// 解析银行返回
			if(tmpStrRet[0].length() == 0) {
				WriteBankLogLn("111银行返回的报文为：" + tmpStrRet[1]);
				String respXml = Base64Helper.getFromBase64(tmpStrRet[1].split(",")[0], getCharset());

				WriteBankLogLn("银行返回的报文为：" + respXml);

				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);

				if(tmpBkReader != null) {
					String tmpRespCode = tmpBkReader.getFirstText("/Response/Head/Code");

					if (tmpRespCode.equals("2000")) {
						respCode = "0";
						respInfo = "";

						retAts.busDate = Format.Date10Format.format(p_reqQrySttm.getBusDate());
						retAts.totalNum = tmpBkReader.getFirstText("/Response/Head/TotalCount");

						if (tmpBkReader.read("/Response/Body/Tx")) {
							while(tmpBkReader.read("/Response/Body/Tx")) {
								RetAtsStatementDetail p_retDetail = new RetAtsStatementDetail();

								p_retDetail.askNumber = tmpBkReader.readedXElement.getSingleText("TxSn");
								p_retDetail.amount = tmpBkReader.readedXElement.getSingleText("TxAmount");
								p_retDetail.busType = tmpBkReader.readedXElement.getSingleText("TxType");
								p_retDetail.fee = tmpBkReader.readedXElement.getSingleText("InstitutionFee");
								p_retDetail.transMsg = tmpBkReader.readedXElement.getSingleText("Remark");
								p_retDetail.transState = TransState.Success;

								retAts.writeRetDetail(p_retDetail);
							}
						}else {
							respCode = "-1";
							respInfo = "本日未产生交易或本日对账单尚未生成";
						}
					}else {
						respCode = "-1";
						respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
					}
				}else {
					respCode = "-1";
					respInfo = tmpSbMsg.toString();
				}
			}else{
				respCode = "-1";
				respInfo = tmpStrRet[1];
			}

			if (!respCode.equals("0")) {
				retAts.writeRespCode(respCode);
				retAts.writeRespInfo(respInfo);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		return respHeader;
	}

	private String[] getStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"", ""};

		String respCode = "";
		String respInfo = "";
		retAts.totalNum = "0";
		int totalNum = 0;
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "*");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				if (actItem == null) {
					throw new Exception("未找到账号" + p_reqQrySttm.actNum + "对应的商户配置节点");
				} else {
					throw new Exception("账号" + p_reqQrySttm.actNum + "对应的证书文件不存在");
				}
			}

			// 拼请求报文
			CPCN01Header bankHeader = new CPCN01Header();
			bankHeader.transCode = "1810";

			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, bankHeader);

			xmlWriter.writeElementString("TxCode", bankHeader.transCode);
			xmlWriter.writeEndElement();
			xmlWriter.writeStartElement("Body");
			xmlWriter.writeElementString("InstitutionID", actItem.merchantId);
			xmlWriter.writeElementString("Date", Format.Date10Format.format(p_reqQrySttm.getBusDate()));
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();

			// 请求报文
			WriteBankLogStep2(xmlWriter.toXmlString());

			// 发送银行
			String[] tmpStrRet = sendToBank("sync", xmlWriter.toXmlString(), actItem);

			// 解析银行返回
			if(tmpStrRet[0].length() == 0) {
				WriteBankLogLn("111银行返回的报文为：" + tmpStrRet[1]);
				String respXml = Base64Helper.getFromBase64(tmpStrRet[1].split(",")[0], getCharset());

				WriteBankLogLn("银行返回的报文为：" + respXml);

				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);

				if(tmpBkReader != null) {
					String tmpRespCode = tmpBkReader.getFirstText("/Response/Head/Code");

					if (tmpRespCode.equals("2000")) {
						respCode = "0";
						respInfo = "";

						retAts.busDate = Format.Date10Format.format(p_reqQrySttm.getBusDate());
						if (tmpBkReader.read("/Response/Body/Tx")) {
							while(tmpBkReader.read("/Response/Body/Tx")) {
								totalNum ++;
								RetAtsStatementDetail p_retDetail = new RetAtsStatementDetail();

								p_retDetail.askNumber = tmpBkReader.readedXElement.getSingleText("TxSn");
								p_retDetail.amount = tmpBkReader.readedXElement.getSingleText("TxAmount");
								p_retDetail.busType = tmpBkReader.readedXElement.getSingleText("TxType");
								p_retDetail.fee = tmpBkReader.readedXElement.getSingleText("InstitutionFee");
								p_retDetail.transMsg = tmpBkReader.readedXElement.getSingleText("Remark");
								p_retDetail.transState = TransState.Success;
								retAts.writeRetDetail(p_retDetail);
							}
						}else {
							respCode = "-1";
							respInfo = "本日未产生交易或本日对账单尚未生成";
						}
					}else {
						respCode = "-1";
						respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
					}
				}else {
					respCode = "-1";
					respInfo = tmpSbMsg.toString();
				}
			}else{
				respCode = "-1";
				respInfo = tmpStrRet[1];
			}

			if (!respCode.equals("0")) {
				retAts.writeRespCode(respCode);
				retAts.writeRespInfo(respInfo);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		return respHeader;
	}
}
